package thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 解决线程安全问题方式三：通过Lock锁来实现
 *
 * synchronized和Lock的异同：
 * 1、相同：都用于解决线程同步的问题
 * 2、异同：synchronized关键字修改的方法或代码块是自动加锁和解锁监视器，Lock是通过对象手动方式进行加锁和解锁
 * 解决线程同步一般几种方式：两种
 *
 * @author: apple
 * @date:  2021/11/28 4:26 下午
 * @version 1.0
 **/
public class LockTest {
    public static void main(String[] args) {
        W w = new W();
        Thread t1 = new Thread(w , "窗口1");
        Thread t2 = new Thread(w , "窗口2");
        Thread t3 = new Thread(w , "窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class W implements Runnable {
    private int ticket = 100;

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {

            try {

                //加锁
                lock.lock();

                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "售票，票号为：" + ticket);
                    ticket--;
                } else {
                    break;
                }
            } finally {

                // 解锁
                lock.unlock();
            }


        }
    }
}
